package com.example.onlinemusic.controller;

import com.example.onlinemusic.mapper.LoveMusicMapper;
import com.example.onlinemusic.mapper.MusicMapper;
import com.example.onlinemusic.model.Music;
import com.example.onlinemusic.model.User;
import com.example.onlinemusic.tools.Constant;
import com.example.onlinemusic.tools.ResponseBodyMessage;
import org.apache.ibatis.binding.BindingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/music")
public class MusicController {

    @Value("${music.local.path}")
//    private String SAVE_PATH="E:/music1/";
    private String SAVE_PATH;

    @Autowired
    private MusicMapper musicMapper;

    @Resource
    private LoveMusicMapper loveMusicMapper;

    @RequestMapping("/upload")
    public ResponseBodyMessage<Boolean> insertMusic(@RequestParam String singer,
                                                    @RequestParam("filename")MultipartFile file,
                                                    HttpServletRequest request,
                                                    HttpServletResponse resp)  {
        HttpSession httpSession=request.getSession(false);
        if(httpSession==null||httpSession.getAttribute(Constant.USERINFO_SESSION_KEY)==null){
            System.out.println("没有登陆~");
            return new ResponseBodyMessage<>(-1,"请登陆后上传",false);
        }
        String fileNameAndType=file.getOriginalFilename();
        System.out.println("fileNameAndType: "+fileNameAndType);
        String path=SAVE_PATH+"/"+fileNameAndType;
        File dest=new File(path);
        if(!dest.exists()){
            dest.mkdir();
        }
        try {
            file.transferTo(dest);
//            return new ResponseBodyMessage<>(0,"上传成功~",true);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1,"服务器上传失败！",false);
        }

        int index=fileNameAndType.lastIndexOf(".");
        String title=fileNameAndType.substring(0,index);
        User user=(User)httpSession.getAttribute(Constant.USERINFO_SESSION_KEY);
        int userId=user.getId();

        String url="/music/get?path="+title;
        SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
        String time=sf.format(new Date());

        try{
            int ret=0;
            ret=musicMapper.insert(title,singer,time,url,userId);
            if(ret==1){
                try {
                    resp.sendRedirect("/list.html");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return new ResponseBodyMessage<>(0,"数据库上传成功~",true);
            }else {
                return new ResponseBodyMessage<>(-1,"数据库上传失败！",false);
            }
        }catch (BindingException e){
            dest.delete();
            return new ResponseBodyMessage<>(-1,"数据库上传失败！",false);

        }
    }

    @RequestMapping("/get")
    public ResponseEntity<byte[]> get(String path){
        File file=new File(SAVE_PATH+"/"+path);
        byte[] a = null;
        try {
            a= Files.readAllBytes(file.toPath());
            if(a==null){
                return ResponseEntity.badRequest().build();
            }
            return ResponseEntity.ok(a);
        } catch (IOException e) {
            e.printStackTrace();
        }
          return ResponseEntity.badRequest().build();
//        return ResponseEntity.internalServerError().build();
//        return ResponseEntity.notFound().build();
    }

    @RequestMapping("/delete")
    public ResponseBodyMessage<Boolean> deleteMusicById(@RequestParam String id){
        int iid=Integer.parseInt(id);
        Music music=musicMapper.findMusicById(iid);
        if(music==null){
            System.out.println("没有找到此id的音乐。");
            return new ResponseBodyMessage<>(-1,"你想要删除的音乐不存在。",false);

        }else {
            int ret=musicMapper.deleteMusicById(iid);
            if(ret==1){
                int index=music.getUrl().lastIndexOf("=");
                String fileName=music.getUrl().substring(index+1);
                File file=new File(SAVE_PATH+"/"+fileName+".mp3");
                System.out.println("当前路径： "+file.getPath());

                if(file.delete()){
                    loveMusicMapper.deleteLoveMusicByMusicId(iid);
                    return new ResponseBodyMessage<>(1,"服务器中的音删除成功~",true);
                }else {
                    return new ResponseBodyMessage<>(-1,"服务器中的音乐删除失败！",false);
                }
            }else {
                return new ResponseBodyMessage<>(-1,"数据库中的音乐未删除成功。",false);

            }
        }
    }

    @RequestMapping("/deleteSel")
    public ResponseBodyMessage<Boolean> deleteSelMusic(@RequestParam("id[]")List<Integer> id){
        System.out.println("所有的id： "+id);
        int sum=0;
        for (int i = 0; i <id.size(); i++) {
            int musicId=id.get(i);
            Music music=musicMapper.findMusicById(musicId);
            if(music==null){
                System.out.println("没有找到此id的音乐。");
                return new ResponseBodyMessage<>(-1,"你想要删除的音乐不存在。",false);
            }
            int ret=musicMapper.deleteMusicById(musicId);
            if(ret==1){
                int index=music.getUrl().lastIndexOf("=");
                String fileName=music.getUrl().substring(index+1);
                File file=new File(SAVE_PATH+"/"+fileName+".mp3");
                System.out.println("当前路径： "+file.getPath());

                if(file.delete()){
                    loveMusicMapper.deleteLoveMusicByMusicId(musicId);
                    sum+=ret;
                    //return new ResponseBodyMessage<>(1,"服务器中的音乐删除成功~",true);
                }else {
                    return new ResponseBodyMessage<>(-1,"服务器中的音乐删除失败！",false);
                }
            }else {
                return new ResponseBodyMessage<>(-1,"数据库中的音乐删除失败！",false);
            }
        }
        if(sum==id.size()){
            System.out.println("删除成功~");
            return new ResponseBodyMessage<>(1,"批量删除成功~",true);
        }else {
            System.out.println("删除失败！");
            return new ResponseBodyMessage<>(-1,"批量删除失败！",false);
        }
    }
    @RequestMapping("/findmusic")
    public ResponseBodyMessage<List<Music>> findMusic(@RequestParam(required = false) String musicName){
        List<Music> musicList=null;
        if(musicName!=null){
            musicList=musicMapper.findMusicByName(musicName);
        }else {
            musicList=musicMapper.findMusic();
        }
        return new ResponseBodyMessage<>(1,"此处查询了所有音乐~",musicList);
    }
}


















